package com.zzb.demo.service.impl;

import com.zzb.demo.model.domain.Account;
import com.zzb.demo.service.SpringService;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author zzb
 * @Date 2024/11/26 10:54
 * @Version 1.0
 * @description
 */
@Data
public class SpringServiceImpl implements SpringService {
    private final static Logger LOGGER = LoggerFactory.getLogger(SpringServiceImpl.class);
    private JdbcTemplate jdbcTemplate;

    public void createDb() {
        jdbcTemplate.execute("create table account(\n" +
                "    id int primary key auto_increment,\n" +
                "    username varchar(20),\n" +
                "    balance double\n" +
                ")");
        LOGGER.info("account表创建成功");
    }

    @Override
    public int addAccount(Account account) {
        String sql = "insert into account(username,balance) value(?,?)";
        Object[] obj = new Object[]{
                account.getUsername(),
                account.getBalance()
        };
        return jdbcTemplate.update(sql, obj);
    }

    @Override
    @Transactional
    public int updateAccount(Account account) {
        String sql = "update account set username=?,balance=? where id=?";
        Object[] params = new Object[]{
                account.getUsername(),
                account.getBalance(),
                account.getId()
        };
        int update = jdbcTemplate.update(sql, params);
        return update;
    }

    @Override
    public int deleteAccount(int id) {
        String sql = "delete from account where id=?";
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public List<Account> findAllAccount() {
        String sql = "select * from account";
        BeanPropertyRowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
        return jdbcTemplate.query(sql, rowMapper);
    }


}
